<template>
    <div class="search-box">
        <i class="icon-search"></i>
        <input class="box" v-model="query" :placeholder="placeholder" ref="input">
        <i class="icon-dismiss" @click="clear" v-show="query"></i>
    </div>
</template>

<script>
import { debounce } from 'common/js/util'

export default {
    props: {
        placeholder: {
            type: String,
            default: '搜索歌曲、歌手'
        }
    },
    data() {
        return {
            query: '',
            timer: null
        }
    },
    methods: {
        clear() {
            this.query = ''
        },
        addQuery(query) {
            this.query = query
        },

        // 自动获取input焦点
        autoFocus() {
            this.$nextTick(x => {
                this.$refs.input.focus()
            })
        },

        sendQuery(newQuery) {
            this.$emit('query', newQuery)
        },

        // 手机端上滚动会取消键盘显示
        blur() {
            this.$refs.input.blur()
        }
    },
    created() {
        // $watch跟watch()钩子功能一样
        this.$watch('query', debounce((newQuery) => {
            this.$emit('query', newQuery)
        }, 200))
        this.autoFocus()
    },
    watch: {
        // 监听query的变化
        // query(newQuery) {
        //     console.log(newQuery)
        //     if (this.timer) {
        //         clearTimeout(this.timer)
        //     }
        //     this.timer = setTimeout(() => {
        //         this.$emit('query', newQuery)
        //     }, 1000)
        // }
    }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"

  .search-box
    display: flex
    align-items: center
    box-sizing: border-box
    width: 100%
    padding: 0 6px
    height: 40px
    background: $color-highlight-background
    border-radius: 6px
    .icon-search
      font-size: 24px
      color: $color-background
    .box
      flex: 1
      margin: 0 5px
      line-height: 18px
      background: $color-highlight-background
      color: $color-text
      font-size: $font-size-medium
      &::placeholder
        color: $color-text-d
    .icon-dismiss
      font-size: 16px
      color: $color-background
</style>
